package com.smarttiger.zero.admin.service;

import com.smarttiger.zero.admin.dao.TaskDao;
import com.smarttiger.zero.admin.dao.TaskLogicDao;
import com.smarttiger.zero.admin.entity.TaskLogicModel;
import com.smarttiger.zero.admin.entity.TaskModel;
import com.smarttiger.zero.admin.task.QuartzScheduler;
import com.smarttiger.zero.admin.util.ParamNames;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
public class TaskLogicService extends BaseService<TaskLogicModel> {
    @Autowired
    TaskLogicDao dao;

    @Autowired
    TaskDao taskDao;

    @Autowired
    private QuartzScheduler quartzScheduler;

    @PostConstruct
    public void initMethod() {
        super.setDao(dao);
    }

    @ParamNames("taskId")
    public List<TaskLogicModel> findLogicByTaskId(String taskId){
        return dao.getTaskLogicModelByTaskId(taskId);
    }

    @Override
    public void save(TaskLogicModel u) {
        TaskModel one = taskDao.findById(u.getTaskId()).get();
        try {
            quartzScheduler.deleteJob(one.getCode());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        super.save(u);
    }

    @Override
    public void update(TaskLogicModel u) {
        TaskModel one = taskDao.findById(u.getTaskId()).get();
        try {
            quartzScheduler.deleteJob(one.getCode());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        super.update(u);
    }

    @Override
    public void delete(String id) {
        TaskModel one = taskDao.findById(dao.findById(id).get().getTaskId()).get();
        try {
            quartzScheduler.deleteJob(one.getCode());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        super.delete(id);
    }
}
